const WebSocket = require('ws');
var fs = require('fs');// 引入fs 模块

var limit = true;
var watch = require('watch');
var chokidar = require('chokidar');

var wss;
function noop() {}

function heartbeat() {
    this.isAlive = true;
}
//
const interval = setInterval(function ping() {
    wss.clients.forEach(function each(ws) {
        if (ws.isAlive === false) return ws.terminate();

        ws.isAlive = false;
        ws.ping(noop);
    });
}, 30000);
function thcat_watch(cb) {
    var watcher = chokidar.watch('file, dir, or glob', {
        ignored: /[\/\\]\./, persistent: true
    });

    var log = console.log.bind(console);
    // console.log("new");
    watcher
        .on('add', function (path) {
            log('File', path, 'has been added');
        })
        .on('addDir', function (path) {
            log('Directory', path, 'has been added');
        })
        .on('change', function (path) {
            // if(~path.indexOf(".idea")){
            //         return;
            //     }
            log('File', path, 'has been changed');
        })
        .on('unlink', function (path) {
            log('File', path, 'has been removed');
        })
        .on('unlinkDir', function (path) {
            log('Directory', path, 'has been removed');
        })
        .on('error', function (error) {
            log('Error happened', error);
        })
        .on('ready', function () {
            log('Initial scan complete. Ready for changes.');
        })
        .on('raw', function (event, path, details) {
            if (( ~path.indexOf("css") || ~path.indexOf("html") || ~path.indexOf("js") ) && limit) {
                console.log(new Date());
                //不知为何 会自己 触发4次 加个限制

                limit = false;
                setTimeout(function () {
                    limit = true
                    cb();
                    return;
                    if(ws.readyState !== 1){
                        // init_handle();
                        return;
                    }
                        ws.send("wx",function ack (error) {
                            //  如果未定义错误，则发送已完成，否则发生错误
                            //  对象将指示失败的内容。
                            console.log("page___");
                            console.log(error);
                            console.log("socket.readyState ")
                            console.log(ws.readyState);
                            if(ws.readyState == 3 ){
                                console.log("3333333333");
                                // ws.close()
                                // ws.open()
                                console.log("readYstate________________________-")
                                console.log(ws.readyState)
                            }
                            if(!error){

                            }else{
                                var  err= JSON.stringify(error);
                                if(~err.indexOf("Error")){
                                    init_wss()
                                }

                                console.log(!! err.indexOf("Error"))
                            }

                           // init_wss();
                        })
                }, 500);
            }
            // log('Raw event info:', event, path, details);
        });
}

function init_wss() {
    wss = new WebSocket.Server({ port: 7000 });
    init_handle();
}

function init_handle() {
    wss.on('connection', function connection(ws) {
        console.log("connect")
        wss.on('message', function incoming(message) {
            console.log('received: %s', message);
        });
        wss.on('close', function close() {
            console.log('disconnected')
        });
        wss.on("error",function (e) {
            console.log("error");
            console.log(e);
            // wss = new WebSocket.Server({ port: 7000 });
            // init_wss();
        })
        ws.isAlive = true;
        ws.on('pong', heartbeat);

        // ws.send('something');
        thcat_watch(function () {
            ws.send("reload",function (e) {
                console.log("send_reload__________---");
                console.log(e);
            });
            
        });

    });
   //
   // wss.on("close",function () {
   //     console.log("close")
   //     init_wss();
   // })



}


init_wss();